<template>
  <div class="history-page">
    <van-nav-bar
      title="浏览历史"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      right-text="清空"
      @click-right="clearHistory"
    />
    
    <div class="history-content">
      <div v-if="historyGroups.length > 0">
        <div v-for="(group, groupIndex) in historyGroups" :key="groupIndex" class="history-group">
          <div class="group-date">{{ group.date }}</div>
          
          <div class="history-list">
            <div 
              v-for="(item, index) in group.items" 
              :key="item.id" 
              class="history-item"
              @click="viewHistoryItem(item)"
            >
              <div class="item-time">{{ formatTime(item.time) }}</div>
              <div class="item-content">
                <div v-if="item.cover" class="item-cover">
                  <img :src="item.cover" :alt="item.title">
                </div>
                <div class="item-info">
                  <div class="item-title">{{ item.title }}</div>
                  <div class="item-type">{{ getTypeLabel(item.type) }}</div>
                </div>
              </div>
              <div class="item-delete" @click.stop="deleteHistoryItem(item)">
                <van-icon name="delete" />
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <van-empty v-else description="暂无浏览记录" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'

const router = useRouter()
const historyItems = ref([])

// 按日期分组的历史记录
const historyGroups = computed(() => {
  const groups = []
  const groupMap = {}
  
  historyItems.value.forEach(item => {
    const date = new Date(item.time)
    const dateString = formatDate(date)
    
    if (!groupMap[dateString]) {
      groupMap[dateString] = {
        date: dateString,
        items: []
      }
      groups.push(groupMap[dateString])
    }
    
    groupMap[dateString].items.push(item)
  })
  
  return groups
})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 查看历史项目
const viewHistoryItem = (item) => {
  switch (item.type) {
    case 'article':
      router.push(`/blog/${item.id}`)
      break
    case 'weather':
      router.push(`/weather/${item.id}`)
      break
    default:
      router.push(`/${item.type}/${item.id}`)
  }
}

// 删除历史项目
const deleteHistoryItem = (item) => {
  showDialog({
    title: '确认删除',
    message: '确定要删除这条浏览记录吗？',
    showCancelButton: true
  }).then(() => {
    historyItems.value = historyItems.value.filter(i => i.id !== item.id)
    showToast('已删除')
  }).catch(() => {
    // 取消操作
  })
}

// 清空所有历史
const clearHistory = () => {
  if (historyItems.value.length === 0) {
    showToast('暂无浏览记录')
    return
  }
  
  showDialog({
    title: '确认清空',
    message: '确定要清空所有浏览记录吗？',
    showCancelButton: true
  }).then(() => {
    historyItems.value = []
    showToast('已清空')
  }).catch(() => {
    // 取消操作
  })
}

// 获取类型标签
const getTypeLabel = (type) => {
  const typeMap = {
    article: '文章',
    video: '视频',
    weather: '天气',
    product: '商品'
  }
  
  return typeMap[type] || type
}

// 格式化日期
const formatDate = (date) => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  
  if (date >= today) {
    return '今天'
  } else if (date >= yesterday) {
    return '昨天'
  } else {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }
}

// 格式化时间
const formatTime = (dateString) => {
  const date = new Date(dateString)
  return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 加载历史记录
const loadHistory = () => {
  // 模拟获取历史记录数据
  // 实际项目中应该从本地存储或API获取
  
  const now = new Date()
  
  // 今天的历史
  const todayItems = Array(5).fill(0).map((_, index) => ({
    id: `today-${index}`,
    title: `浏览的文章标题 ${index}`,
    type: 'article',
    time: new Date(now.getFullYear(), now.getMonth(), now.getDate(), 
                  now.getHours() - index % 3, 
                  now.getMinutes() - index * 7).toISOString(),
    cover: index % 2 === 0 ? `https://picsum.photos/id/${200 + index}/100/100` : undefined
  }))
  
  // 昨天的历史
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  
  const yesterdayItems = Array(3).fill(0).map((_, index) => ({
    id: `yesterday-${index}`,
    title: `昨天浏览的${index === 0 ? '天气' : '文章'} ${index}`,
    type: index === 0 ? 'weather' : 'article',
    time: new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 
                  14 + index, 
                  index * 15).toISOString(),
    cover: index !== 0 ? `https://picsum.photos/id/${210 + index}/100/100` : undefined
  }))
  
  // 更早的历史
  const daysAgo = new Date(now)
  daysAgo.setDate(daysAgo.getDate() - 3)
  
  const earlierItems = Array(2).fill(0).map((_, index) => ({
    id: `earlier-${index}`,
    title: `更早浏览的${index === 0 ? '视频' : '商品'} ${index}`,
    type: index === 0 ? 'video' : 'product',
    time: new Date(daysAgo.getFullYear(), daysAgo.getMonth(), daysAgo.getDate(), 
                  10 + index, 
                  index * 30).toISOString(),
    cover: `https://picsum.photos/id/${220 + index}/100/100`
  }))
  
  historyItems.value = [...todayItems, ...yesterdayItems, ...earlierItems]
}

onMounted(() => {
  loadHistory()
})
</script>

<style lang="scss" scoped>
.history-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: var(--tabbar-height);
  
  .history-content {
    padding: 0 0 20px;
    
    .history-group {
      margin-bottom: 16px;
      
      .group-date {
        padding: 10px 16px;
        font-size: 14px;
        font-weight: 500;
        color: var(--text-color);
        background-color: var(--background-color);
        position: sticky;
        top: 0;
        z-index: 1;
      }
      
      .history-list {
        .history-item {
          display: flex;
          flex-direction: column;
          padding: 12px 16px;
          border-bottom: 1px solid var(--border-color-light);
          position: relative;
          
          .item-time {
            font-size: 12px;
            color: var(--text-color-tertiary);
            margin-bottom: 4px;
          }
          
          .item-content {
            display: flex;
            
            .item-cover {
              width: 64px;
              height: 64px;
              border-radius: 4px;
              overflow: hidden;
              margin-right: 12px;
              flex-shrink: 0;
              
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            
            .item-info {
              flex: 1;
              
              .item-title {
                font-size: 15px;
                color: var(--text-color);
                margin-bottom: 4px;
                line-height: 1.4;
              }
              
              .item-type {
                display: inline-block;
                padding: 2px 6px;
                font-size: 12px;
                color: var(--primary-color);
                background-color: rgba(var(--primary-color-rgb), 0.1);
                border-radius: 4px;
              }
            }
          }
          
          .item-delete {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-color-tertiary);
            padding: 8px;
          }
        }
      }
    }
  }
}
</style> 